#pragma once
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
namespace protocol_ns
{
    const std::string SEP("\r\n");
    std::string Encode(std::string json_ptr)
    {
        int len=json_ptr.size();
        std::string ret=std::to_string(len);
        ret+=SEP;
        ret+=json_ptr;
        ret+=SEP;
        return ret;
    }
    std::string Decode(std::string&inbuffer)
    {
        size_t pos=inbuffer.find(SEP);
        if(pos==std::string::npos)return "";
        std::string len_str=inbuffer.substr(0,pos);
        int len=std::stoi(len_str);
        int total=len_str.size()+2*SEP.size()+len;
        if(inbuffer.size()<total)return "";
        std::string json_str=inbuffer.substr(pos+SEP.size(),len);
        inbuffer.erase(0,total);
        return json_str;
    }
    class Request
    {
    public:
        Request() {}
        ~Request() {}
        bool Serialize(std::string *out)
        {
            // 将结构化的数据转化为字符串输出
            Json::Value root;
            root["x"] = _x;
            root["y"] = _y;
            root["oper"] = _oper;
            Json::FastWriter writer;
            *out = writer.write(root);
            return true;
        }
        bool DeSerialize(std::string &in)
        {
            // 将给定的字符串转化为结构化的数据
            Json::Value root;
            Json::Reader reader;
            bool res = reader.parse(in, root);
            if (res == false)
                return false;
            _x = root["x"].asInt();
            _y = root["y"].asInt();
            _oper = root["oper"].asInt();
            return true;
        }

    public:
        int _x=0;
        int _y=0;
        char _oper=0; //+-*/%   43 45 42 47 37
    };
    class Response
    {
    public:
        Response() {}
        ~Response() {}
        bool Serialize(std::string *out)
        {
            // 将结构化的数据转化为字符串输出
            Json::Value root;
            root["result"] = _result;
            root["code"] = _code;
            Json::FastWriter writer;
            *out = writer.write(root);
            return true;
        }
        bool DeSerialize(std::string &in)
        {
            // 将给定的字符串转化为结构化的数据
            Json::Value root;
            Json::Reader reader;
            bool res = reader.parse(in, root);
            if (res == false)
                return false;
            _result = root["result"].asInt();
            _code = root["code"].asInt();
            return true;
        }
    public:
        int _result=0;
        int _code=0; // 0.结果无异议 1.除零或模零 2.不认识运算符
    };
}